'use strict';

exports.main = async (event) => {
    const { page = 1, pageSize = 2, userOpenid } = event
    const skipCount = (page - 1) * pageSize

    const db = uniCloud.database();
    const todos = db.collection('post-data')

    try {
        let query = {}
        if (userOpenid) {
            query = { openid: userOpenid }
        }

        const res = await performQuery(todos, query, skipCount, pageSize);
        return res
    } catch (error) {
        return { error: '查询失败' }
    }
};

async function performQuery(todos, query, skipCount, pageSize) {
    return await todos
        .where(query)
        .orderBy('_id', 'desc')
        .skip(skipCount)
        .limit(pageSize)
        .get()
}